<!--配置私信黑名单-->
<script setup>
import {onMounted, ref} from "vue";
import {useStore} from "vuex";
import {ElMessageBox} from "element-plus";
import {ElementUtils} from "@/assets/js/ElementUtils";
import UserLink from "@/components/common/link/UserLink.vue";
import {DeleteFilled} from "@element-plus/icons-vue";

const store = useStore();

const users = ref();

const getUserInfoById = (id) => store.dispatch("User/userInfoGetById", {id})
const getUserInfoByUsername = (username) => store.dispatch("User/userInfoGetByName", {username})

const list = (force) => {
  const loading = ElementUtils.loading({target: "#pm_block_config",});
  return store.dispatch("Message/pmBlockList", force).then(res => {
    console.log(res)
    users.value = res;
  }).catch(ElementUtils.exceptionHandler).finally(() => {
    loading.close()
  });
}
const add = () => ElMessageBox.prompt(undefined, "添加私信黑名单", {
  inputPlaceholder: "请输入用户ID或用户名",
}).then(async ({value, action}) => {
  if (action === 'confirm') {
    console.log(value)
    const uid = Number(value)
    const userInfo = isNaN(uid) ?
        await getUserInfoByUsername(value) : await getUserInfoById(uid)

    const {userId, username} = userInfo
    const res = await store.dispatch("Message/pmBlockAdd", userId)
    ElementUtils.notice({message: res})
    await list(true)
  }
}).catch(ElementUtils.exceptionHandler).catch(r => {
  console.warn(r)
})
const del = (userId, username) => {
  return ElementUtils.confirm(`即将把用户 ${username}(${userId}) 移出私信黑名单`, "移出黑名单").then(async () => {
    const res = await store.dispatch("Message/pmBlockDel", userId);
    ElementUtils.notice({message: res})
    await list(true)
  }).catch(ElementUtils.exceptionHandler).catch(r => {
    console.warn(r)
  })
}

onMounted(() => {
  list();
})

</script>

<template>
  <div id="pm_block_config">
    <!--  操作按钮-->
    <div>
      <el-button-group type="primary">
        <el-button @click="list(true)">刷新</el-button>
        <el-button type="success" @click="add">添加</el-button>
      </el-button-group>
    </div>
    <!--  名单-->
    <div>
      <ul>
        <li v-if="!users || users.length===0">暂无</li>
        <li v-for="{userId,username} in users" v-else>
          <user-link :user-id="userId">{{ username }}</user-link>

          <el-icon color="red" style="cursor: pointer" @click="del(userId,username)">
            <DeleteFilled/>
          </el-icon>
        </li>
      </ul>
    </div>
  </div>
</template>

<style scoped>
#pm_block_config {
  min-height: 100px;
}
</style>